package model
{
	import core.Model;
	import global.GameState;
	
	import events.HallEvent;
	import events.LoginEvent;
	
	import flash.events.Event;

	public class Robot
	{
		private static var instance:Robot;
		
		private var _model:Model = Model.getInstance();
		private var _data:XML;
		
		public function Robot()
		{
			if (instance)
			{
				throw Error("单列");
			}
			
		}
		
		public static function getInstance():Robot
		{
			if (instance == null) 
			{
				instance = new Robot();
				if (GameState.isRobot == "1")
				{
					instance.initListeners();
				}
			}
			return instance;
		}
		
		private function initListeners():void
		{
			_model.hallModel.addEventListener(HallEvent.ROOM_XML_COMPLETE,onRoomXmlComplete);
			_model.netSocket.addEventListener(Event.CONNECT,onConnected);
			_model.loginModel.addEventListener(LoginEvent.ACCESSSERVER_LOGINING,onLoginAccess);
			
		}
		
		private function onLoginAccess(e:LoginEvent):void
		{
			if (_data)
			{
				//loginGameServer();
			}
		}
		
		private function onConnected(e:Event):void
		{
			if (GameState.isRobot != "1")
			{
				return;
			}
			
			if (!GameState.isRobotStart)
			{
				_model.tableModel.gotoHall();
			}
			
			
		}
		
		private function onRoomXmlComplete(e:HallEvent):void
		{
			_data = _model.hallModel.roomListXml;
			if (!GameState.isRobotStart)
			{
				loginGameServer();
			}
		}
		
		public function isStart():void
		{
			if (GameState.isRobot != "1")
			{
				return;
			}
			
			if (GameState.isRobotStart)
			{
				GameState.isRobotStart = false;
				loginGameServer();
			}
			else
			{
				GameState.isRobotStart = true;
			}
		}
		
		private function loginGameServer():void
		{
			GameState.isQuickGame = 0;
			var item:XML = _data.children()[0];
			var gameServerIp:String = item.@ip;
			var port:int = int(item.@port);
			var roomId:String = item.@id;
			_model.loginModel.loginGameServer(roomId,gameServerIp,port);
		}
		
	
	}
}